package cn.regexp.greenway.service;

import cn.hutool.core.util.NumberUtil;
import cn.regexp.greenway.pojo.LocationPoint;
import cn.regexp.greenway.pojo.Route;
import cn.regexp.greenway.utils.TimeUtils;
import cn.regexp.greenway.utils.UserThreadLocal;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Service
public class RouteInfoService {

    @Autowired
    private BaiduService baiduService;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新路线数据，查询鹰眼服务中的轨迹数据，更新到MongoDB中
     *
     * @param routeId   路线ID
     * @param userId    用户ID
     * @return
     */
    @Async
    public CompletableFuture<String> updateRouteInfo(String routeId, Long userId) {
        // 异步执行，需要将用户ID存储到当前线程中，baiduService服务中才能获取到
        UserThreadLocal.set(userId);

        // 根据路线ID查询路线数据（MongoDB）
        Route route = mongoTemplate.findById(new ObjectId(routeId), Route.class);
        if (route == null) {
            return null;
        }

        Long startTime = route.getStartTime() / 1000;
        Long endTime = route.getEndTime() / 1000;

        // 查询轨迹数据
        Route routeEntity = baiduService.queryEntity(routeId, startTime, endTime);
        if (routeEntity == null) {
            return CompletableFuture.completedFuture("error");
        }

        String time;
        try {
            time = TimeUtils.formatTime((routeEntity.getEndPoint().getLocTime() - routeEntity.getStartPoint().getLocTime()));
        } catch (Exception e) {
            time = "00:00";
        }
        double speed;
        try {
            speed = routeEntity.getPoints().stream().mapToDouble(LocationPoint::getSpeed).sum() / routeEntity.getSize();
            speed = NumberUtil.round(speed, 2).doubleValue();
        } catch (Exception e) {
            speed = 0.00;
        }

        Update update = Update.update("size", routeEntity.getSize())
                .set("distance", NumberUtil.round(routeEntity.getDistance(), 2).doubleValue())
                .set("startPoint", routeEntity.getStartPoint())
                .set("endPoint", routeEntity.getEndPoint())
                .set("points", routeEntity.getPoints())
                .set("location", new GeoJsonPoint(routeEntity.getStartPoint().getLongitude(), routeEntity.getStartPoint().getLatitude()))
                .set("time", time)
                .set("speed", speed);

        Query query = Query.query(Criteria.where("id").is(routeId));
        // 更新数据到MongoDB
        mongoTemplate.updateFirst(query, update, Route.class);

        return CompletableFuture.completedFuture("ok");
    }
}
